﻿package com.atn.edamame.googlews 
{
	import flash.events.*;
	import flash.net.*; 
	import com.atn.edamame.*;
	import com.atn.edamame.tools.*;
	import flash.text.*;
	import org.flashdevelop.utils.FlashConnect;
	public class Translate extends EdamameControl
	{
		private var waitIndex:int = 0;
		public var encode:String = "en|ja";
		public var cache:Object = new Object();


		private function onFail(results:Object) :void
		{

		}
		
		public override function collide(b: EdamameObject):void
		{
			if (b is EdamameString) {
				var con:Translate = this;
				var c:EdamameString = b as EdamameString;
				var onComplete:Function = function onComplete(results:Object):void{
						var o:EdamameString = new EdamameString();
						edamameParent.addEdamameObject(o);
						o.x = con.x;
						//trace(con.y + " " +  con.height);
						o.y = con.y + con.height +  1;
						o.vy = 2;
						o.value = results.responseData.translatedText;
						cache[c.value] = results.responseData.translatedText;
				};
				if (cache[c.value] != null)
				{
					var o:EdamameString = new EdamameString();
					edamameParent.addEdamameObject(o);
					o.x = this.x;
					o.y = this.y + this.height +  1;
					o.vy = 2;
					o.value = cache[c.value];
					b.destroy();
				}else{
					var responder:Responder = new Responder(onComplete, onFail);
					GConnection.getInstance().getConnection().call("googleservice.translate", responder,c.value,encode);
					b.destroy();
				}
			}
		}
		
		public override function exec(variable:Object, onFinish:Function):void
		{
			var responder:Responder = new Responder(function (results:Object):void
			{
				trace("translate exec");
				variable.value = new Array();
				if (results == null)
				{
					onFinish( { result:"ng" } );
					return ;
				}
				variable.value[0] = results.responseData.translatedText;
				onFinish( { result:"ok" } );
			}, onFail);
			
			GConnection.getInstance().getConnection().call("googleservice.translate", responder,variable.value[0],encode);
	
		}
	}
	
}